﻿//变量管理器
//本文件由：贺镇涛（2021300004071）负责
#include"SLLList.h"
#include<string>
using namespace std;
SLList::~SLList()
{
	for (SLLNode* p; !isEmpty();)
	{
		p = head->next;
		delete head;                    //head变为野指针
		head = p;
	}
}

void SLList::addToHead(string name, const std::string& s_info)
{
	head = new SLLNode(name, s_info, head);
	if (tail == 0) tail = head;
	size++;
}

void SLList::addToTail(string name, const std::string& s_info)
{
	if (tail != 0)
	{
		tail->next = new SLLNode(name, s_info);
		tail = tail->next;
	}
	else head = tail = new SLLNode(name, s_info);
	size++;
}

string SLList::deleteFromHead()
{
	string el = head->name;
	SLLNode* tmp = head;
	if (head == tail) head = tail = 0;
	else head = head->next;
	delete tmp;
	size--;
	return el;
}

string SLList::deleteFromTail()
{
	string el = tail->name;
	string e2 = *(tail->info);
	if (head == tail)
	{
		delete head;
		head = tail = 0;
	}
	else
	{
		SLLNode* tmp;
		for (tmp = head; tmp->next != tail; tmp = tmp->next);//目的：循环找到倒数第二个node;
		delete tail;
		tail = tmp;
		tail->next = 0;
	}
	size--;
	return el + e2;
}

std::string* SLList::get_valuePTR(const string& el/*名字*/)
{
	if (head != 0)
	{
		if (el == head->name)
		{
			return head->info;
		}
		else
		{
			SLLNode* pred, * tmp;
			for (
				pred = head, tmp = head->next;
				tmp != NULL && !(tmp->name == el);
				pred = pred->next, tmp = tmp->next
				);
			if (tmp != NULL)
			{
				return tmp->info;
			}
		}
	}
	else return NULL;
}

void SLList::deleteNode(string el)//删除特定值e1的node;
{
	if (head != 0)
	{
		if (head == tail && el == head->name)
		{
			delete head;
			head = tail = 0;
		}
		else if (el == head->name)
		{
			SLLNode* tmp = head;
			head = head->next;
			delete tmp;
		}
		else
		{
			SLLNode* pred, * tmp;
			for (
				pred = head, tmp = head->next;
				tmp != 0 && !(tmp->name == el);
				pred = pred->next, tmp = tmp->next
				);
			if (tmp != 0)
			{
				pred->next = tmp->next;
				if (tmp == tail) tail = pred;
				delete tmp;
			}
		}
	}
	size--;
}

bool SLList::isInlist(string el) const
{
	SLLNode* tmp;
	for (tmp = head; tmp != NULL && !(tmp->name == el); tmp = tmp->next);
	return tmp != 0; //只有当tmp！=0时才返回1
}

int SLList::get_size()
{
	return size;
}
